package com.openroom.ui.component;

import java.net.URL;
import java.util.HashMap;
import java.util.List;

import org.apache.pivot.beans.BXML;
import org.apache.pivot.collections.Map;
import org.apache.pivot.collections.Sequence;
import org.apache.pivot.collections.Sequence.Tree.Path;
import org.apache.pivot.util.Resources;
import org.apache.pivot.util.Vote;
import org.apache.pivot.util.concurrent.TaskExecutionException;
import org.apache.pivot.wtk.TabPane;
import org.apache.pivot.wtk.TabPaneSelectionListener;
import org.apache.pivot.wtk.TreeView;
import org.apache.pivot.wtk.TreeViewSelectionListener;
import org.apache.pivot.wtk.content.TreeBranch;
import org.apache.pivot.wtk.content.TreeNode;
import org.apache.pivot.wtk.media.Image;

import com.openroom.event.ApplicationEvent;
import com.openroom.event.EventHandler;
import com.openroom.event.EventManager;
import com.openroom.event.EventType;
import com.openroom.model.Catalog;
import com.openroom.model.ModelLocator;
import com.openroom.ui.MainWindow;
import com.openroom.ui.NamespaceHelper;
import com.openroom.ui.OPMKeyHandler;
import com.openroom.ui.UIComponent;

public class CatalogTreeView extends TreeView implements UIComponent {

    final URL nodeResource = MainWindow.class.getClassLoader().getResource(
            "com/openroom/ui/folder.png");
    final URL resource = MainWindow.class.getClassLoader().getResource(
            "com/openroom/ui/page_white.png");

    private static HashMap<String, TreeBranch> hashSet = new HashMap<String, TreeBranch>();

    private static boolean initializationComplete = false;

    @BXML
    TabPane leftTabPane;

    public CatalogTreeView() {

    }

    public void initialize() {
        getTreeViewSelectionListeners().add(new CatalogSelectionListener());
        getComponentKeyListeners().add(new OPMKeyHandler());
        EventManager.getInstance().listenToEventType(EventType.INITIALIZATION_COMPLETE, new EventHandler() {
            @Override
            public void handle(ApplicationEvent event) {
                org.apache.pivot.collections.List<Object> treeData = (org.apache.pivot.collections.List<Object>) getTreeData();
                populateCatalogs(treeData, nodeResource, resource);
                initializationComplete = true;
            }
        });
        EventManager.getInstance().listenToEventType(new EventHandler() {
            @Override
            public void handle(ApplicationEvent event) {
                if (initializationComplete)
                {
                    org.apache.pivot.collections.List<Object> treeData = (org.apache.pivot.collections.List<Object>) getTreeData();
                    treeData.clear();
                    hashSet.clear();
                    populateCatalogs(treeData, nodeResource, resource);
                    
                    setTreeData(treeData);
                    System.out.println("new catalog length" + getTreeData().getLength() + treeData.getLength());
                }
            }
        }, EventType.ALL_CATALOG_CHANGED, EventType.IMPORT_COMPLETE);
    }

    void populateCatalogs(org.apache.pivot.collections.List<Object> treeData, URL nodeResource, URL resource) {
        List<Catalog> allCatalogs = ModelLocator.getInstance().getAllCatalogs();
        System.out.println("Model catalog " + allCatalogs.size());
        for (Catalog catalog : allCatalogs) {
            try {
                addCatalog(treeData, nodeResource, resource, catalog);
            } catch (TaskExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    private void addCatalog(org.apache.pivot.collections.List<Object> treeData, URL nodeResource, URL resource,
            Catalog catalog) throws TaskExecutionException {
        if (hashSet.get("" + catalog.getCatalogYear()) == null) {
            int year = 1900 + catalog.getCatalogYear();
            TreeBranch treeBranch = new TreeBranch(
                    Image.load(nodeResource), "" + year);
            treeData.add(treeBranch);
            System.out.println("Adding a new catalog year " + year);
            hashSet.put("" + catalog.getCatalogYear(), treeBranch);
        }
        if (hashSet.get(catalog.getCatalogYear() + "_"
                + catalog.getCatalogMonth()) == null) {
            int month = catalog.getCatalogMonth();
            TreeBranch treeBranch = null;
            switch (month) {
            case 0:
                treeBranch = new TreeBranch(Image.load(nodeResource),
                        "JAN");
                break;
            case 1:
                treeBranch = new TreeBranch(Image.load(nodeResource),
                        "FEB");
                break;
            case 2:
                treeBranch = new TreeBranch(Image.load(nodeResource),
                        "MAR");
                break;
            case 3:
                treeBranch = new TreeBranch(Image.load(nodeResource),
                        "APR");
                break;
            case 4:
                treeBranch = new TreeBranch(Image.load(nodeResource),
                        "MAY");
                break;
            case 5:
                treeBranch = new TreeBranch(Image.load(nodeResource),
                        "JUN");
                break;
            case 6:
                treeBranch = new TreeBranch(Image.load(nodeResource),
                        "JUL");
                break;
            case 7:
                treeBranch = new TreeBranch(Image.load(nodeResource),
                        "AUG");
                break;
            case 8:
                treeBranch = new TreeBranch(Image.load(nodeResource),
                        "SEP");
                break;
            case 9:
                treeBranch = new TreeBranch(Image.load(nodeResource),
                        "OCT");
                break;
            case 10:
                treeBranch = new TreeBranch(Image.load(nodeResource),
                        "NOV");
                break;
            case 11:
                treeBranch = new TreeBranch(Image.load(nodeResource),
                        "DEC");
                break;
            default:
                break;
            }

            TreeBranch treeBranchYear = hashSet.get(""
                    + catalog.getCatalogYear());
            treeBranchYear.add(treeBranch);
            hashSet.put(
                    catalog.getCatalogYear() + "_"
                            + catalog.getCatalogMonth(), treeBranch);
        }
        if (resource != null) {
            TreeBranch treeBranch = hashSet
                    .get(catalog.getCatalogYear() + "_"
                            + catalog.getCatalogMonth());
            TreeNode item = new TreeNode(Image.load(resource), ""
                    + catalog.getCatalogDate());
            item.setUserData(catalog);
            treeBranch.add(item);
        } else {
            TreeBranch treeBranch = hashSet
                    .get(catalog.getCatalogYear() + "_"
                            + catalog.getCatalogMonth());
            System.out.println("adding " + catalog.getCatalogDate());
            TreeNode treeNode = new TreeNode("" + catalog.getCatalogDate());
            treeNode.setUserData(catalog);
            treeBranch.add(treeNode);
        }
    }

    private final class CatalogSelectionListener implements TreeViewSelectionListener {
        @Override
        public void selectedNodeChanged(TreeView arg0, Object arg1) {

        }

        @Override
        public void selectedPathAdded(TreeView arg0, Path arg1) {

        }

        @Override
        public void selectedPathRemoved(TreeView arg0, Path arg1) {

        }

        @Override
        public void selectedPathsChanged(TreeView treeView, Sequence<Path> arg1) {
            TreeNode selectedNode = (TreeNode) treeView
                    .getSelectedNode();
            Catalog catalog = (Catalog) selectedNode.getUserData();
            if (catalog != null) {
                ModelLocator.getInstance().setCurrentlySelectedCatalog(catalog);
            }
        }
    }

    @Override
    public void initialize(Map<String, Object> namespace, URL arg1, Resources arg2, MainWindow window) {
        NamespaceHelper.initialize(namespace, this);
        initialize();
        leftTabPane.getTabPaneSelectionListeners().add(new TabPaneSelectionListener() {

            @Override
            public Vote previewSelectedIndexChange(TabPane arg0, int arg1) {
                return Vote.APPROVE;
            }

            @Override
            public void selectedIndexChangeVetoed(TabPane arg0, Vote arg1) {

            }

            @Override
            public void selectedIndexChanged(TabPane arg0, int arg1) {
                if (arg0.getSelectedIndex() == 0)
                {
                    List<Catalog> allCatalogs = ModelLocator.getInstance().getAllCatalogs();
                    if (!allCatalogs.isEmpty() && getTreeData().getLength() != 0) {
                        expandBranch(new Path(0));
                        expandBranch(new Path(0, 0));
                        setSelectedPath(new Path(0, 0, 0));
                    }
                }
            }

        });
    }
}
